package coop.base.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

@Repository
public class GenericDaoImpl<T> implements GenericDao<T> {

	private Class<T> type;
	
	
	protected EntityManager entityManager;
	
	@PersistenceContext
	public void setEntityManager(EntityManager entityManager){
		this.entityManager = entityManager;
	}
	
	public EntityManager getEntityManager() {
		return entityManager;
	}
	
	public GenericDaoImpl(Class<T> type){
		super();
		this.type = type;
	}
	
	public GenericDaoImpl(){} //eliminar?
	
//	@Transactional(readOnly=true)
	public T get(Long id) {
		if (id == null) {
			return null;
		} else {
			return entityManager.find(type, id);
		}
	}

//	@Transactional(readOnly=true)
	public List<T> getAll() {	
		List<T> resultList = entityManager.createQuery("select p from "+ type.getName() + " p").getResultList();	
		return resultList;
	}

	@Transactional
	public void save(T object) {
		entityManager.persist(object);
	}

	@Transactional
	public void delete(T object) {
		entityManager.remove(entityManager.merge(object));		
	}
	
	

}
